// Vue API
import { ref, shallowRef, onMounted, onUnmounted } from "vue";

// ol API
import { Map, View } from "ol";
import { OverviewMap } from "ol/control";

// Custom ol API
import { addTdtBaseLayer } from "@/utils/ol/layer/baseLayer";
import { tdt_api_key /** 天地图的key */ } from "@/config/keys.json";
import InfoBar from "@/utils/ol/controls/InfoBar";
import Compass from "@/utils/ol/controls/Compass";
import LayersManager from "@/utils/ol/controls/LayersManager";

export default function useInitMap({
  target = "mapContainer",
  projection = "EPSG:4326",
  center = [113.17756338652154, 23.701191837626297],
  zoom = 12,
  onLoadEnd = () => {},
}) {
  let map = shallowRef(null);

  //初始图层
  const layers = [addTdtBaseLayer(tdt_api_key, "vec", "c", "wmts")];

  //初始控件
  const controls = [
    new OverviewMap({
      collapsible: false, //设置为不可折叠
      layers: [addTdtBaseLayer(tdt_api_key, "vec", "c", "wmts")], // 添加图层
    }),
    new InfoBar(),
    new Compass(),
    new LayersManager(),
  ];

  onMounted(() => {
    map.value = new Map({
      view: new View({
        projection,
        center,
        zoom,
      }),
      target,
      controls,
      layers,
    });

    window.map = map.value;

    onLoadEnd(map.value);
  });

  onUnmounted(() => {
    map.value.destroy();
  });

  return {
    map,
  };
}
